package com.wzqj.agent.app.store.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.app.store.service.ApiStoreService;
import com.wzqj.agent.common.ConfigHelper;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.SoaConfig;
import com.wzqj.wsp.response.ResponseValue;
import com.wzqj.wsp.response.ResultStatus;
import com.wzqj.wsp.soa.SOAUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Iterator;

/**
 * Created by wanghao@weipass.cn on 2015/8/4.
 */
@Service("apiStoreService")
public class ApiStoreServiceImpl implements ApiStoreService {

    /**
     * 商户平台服务
     */
    private static final String ALIYUN_URL = ConfigHelper.getProperty("ALIYUN_URL");

    /**
     * 商户平台服务
     */
    private static final String WMP_PROVIDER_APP_CODE = ConfigHelper.getProperty("WMP_PROVIDER_APP_CODE");

    /**
     * 用户店铺列表
     */
    private static final String WMP_USER_STORES_URL = "merchant/getUserMerchantByWhere";
    /**
     * 用户店铺列表  ---调用之前需清除缓存
     */
    private static final String WMP_CLEAN_CACHE = "merchant/cleanCache";
    
    /**
     * 用户店铺数量
     */
    private static final String WMP_USER_STORES_COUNT = "merchant/getUserMerchantCount";
    /**
     * 搜索店铺
     */
    private static final String WMP_STORES_SEARCH_URL = "merchant/getMerchantBySearch";

    /**
     * 运营支撑平台服务
     */
    private static final String ACC_PROVIDER_APP_CODE = ConfigHelper.getProperty("ACC_PROVIDER_APP_CODE");

    /**
     * 店铺详情
     */
    private static final String ACC_USER_STORE_LIST = "merchant/list";

    /**
     * 重置店铺密码
     */
    private static final String ACC_STORE_PASSWORD = "merchant/modifyPassword";

    /**
     * 行业列表
     */
    private static final String ACC_BIZ_CLASSIFY = "bizclassify/list";
    /**
     * 行业列表（新）
     */
    private static final String ACC_BIZ_CLASSIFY_NEW = "bizclassify/listLevelClassify";
    

    /**
     * 添加店铺
     */
    private static final String ACC_MERCHANT_STORE_ADD = "merchant/apply";

    /**
     * 修改店铺
     */
    private static final String ACC_MERCHANT_STORE_UPDATE = "merchant/update";

    /**
     * 店铺下设备数量
     */
    private static final String ACC_MERCHANT_STORE_COUNT = "devices/getCountByMcodes";
    
    /**
     * 店铺下设备信息
     */
    private static final String ACC_STORE_DEVICE = "devices/listByStoreIds";
    
    

    /**
     * 根据资质id获取门店列表
     * @param qualification
     * @return
     */
    @Override
    public JSONArray getStoresByQualification(String qualification) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("qualificationId", qualification);
        //获取数量
        ResponseValue count = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_COUNT, params);
        System.out.println("count:"+count.toString());
        if(count == null){
            if(count.getStatus() == ResultStatus.NO_VALUE_STATUS){
                return new JSONArray();
            }
        }   
        //调用门店之前清除缓存
        ResponseValue rsv = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_CLEAN_CACHE, params);
        System.out.println("rsv:"+rsv.toString());
        //传入分页显示数
        params.put("limit", count.getData());
        //根据资质id获取门店列表接口
        ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, params,soaParam);
        System.out.println("getStoresByQualification:"+res.toString());
        if(res != null){
            if(res.getStatus() == ResultStatus.SUCCESS_STATUS){
            	//组装回传
                JSONArray stores = (JSONArray) res.getData();
                Iterator<Object> iterator = stores.iterator();
                while (iterator.hasNext()){
                    JSONObject store = (JSONObject) iterator.next();
                    String mcode = store.getString("mcode");
                    String busiLicense = store.getString("busiLicense");
                    String busiImgs = store.getString("busiImgs");
                    StringBuffer sb = new StringBuffer();
                    if(!StringUtils.isEmpty(busiImgs)){
                        String[] imgs = busiImgs.split(",");
                        for(String img : imgs){
                            sb.append(ALIYUN_URL).append(img).append(",");
                        }
                    }
                    store.put("busiLicense",StringUtils.isEmpty(busiLicense) ? "" : ALIYUN_URL+busiLicense);
                    store.put("busiImgs",sb.toString());
                    int deviceCount = getStoreCount(mcode);
                    store.put("deviceCount",deviceCount);
                  //处理行业信息格式不统一问题
                    String bizClassify = store.getString("bizClassify");
                    if (!StringUtils.isEmpty(bizClassify)) {
                    	//校验bizClassify为jsonArray格式还是jsonObject格式
                    	char[] strChar = bizClassify.substring(0, 1).toCharArray(); 
                        char firstChar = strChar[0]; 
                        if (firstChar== '{') {
    						JSONObject bizClassifyJO = JSONObject.parseObject(bizClassify);
    						JSONArray bizClassifyJA = new JSONArray();
    						bizClassifyJA.add(bizClassifyJO);
    						System.out.println("getStores--bizClassifyJA:"+bizClassifyJA);
    						store.put("bizClassify", bizClassifyJA);
    					}
    				}
                }
                System.out.println("stores:"+stores);
                return stores;
            }else if(res.getStatus() == ResultStatus.NO_VALUE_STATUS){
                return new JSONArray();
            }
        }
        return null;
    }

    /**
     * 根据店铺id获取店铺详情，长沙接口
     * @param storeid
     * @return
     */
    @Override
    public JSONObject getStoreInfoById(String storeid) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("storeIds", storeid);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_USER_STORE_LIST, params,soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            JSONArray data = (JSONArray) res.getData();
            JSONObject store = data.getJSONObject(0);
            String busiLicense = store.getString("busiLicense");
            String busiImgs = store.getString("busiImgs");
            StringBuffer sb = new StringBuffer();
            if(!StringUtils.isEmpty(busiImgs)){
                String[] imgs = busiImgs.split(",");
                for(String img : imgs){
                    sb.append(ALIYUN_URL).append(img).append(",");
                }
            }
            store.put("busiLicense",StringUtils.isEmpty(busiLicense) ? "" : ALIYUN_URL+busiLicense);
            store.put("busiImgs",sb.toString());
            JSONArray posList = getDevicesByStoreIds(storeid);
            if (posList != null) {
            	store.put("posList", posList);
			}
            
          //处理行业信息格式不统一问题
            String bizClassify = store.getString("bizClassify");
            if (!StringUtils.isEmpty(bizClassify)) {
            	//校验bizClassify为jsonArray格式还是jsonObject格式
            	char[] strChar = bizClassify.substring(0, 1).toCharArray(); 
                char firstChar = strChar[0]; 
                if (firstChar== '{') {
					JSONObject bizClassifyJO = JSONObject.parseObject(bizClassify);
					JSONArray bizClassifyJA = new JSONArray();
					bizClassifyJA.add(bizClassifyJO);
					store.put("bizClassify", bizClassifyJA);
				}
			}
            
            System.out.println("getStoreInfoById--store:"+store);
            return store;
        }
        return null;
    }

    /**
     * 根据mcode获取门店绑定pos所用的用户名和密码
     * @param mcode
     * @return
     */
    @Override
    public JSONObject getStoreAuthInfo(String mcode,String password) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("mcode", mcode);
        params.put("passwd", password);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_STORE_PASSWORD, params,soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            JSONObject data = new JSONObject();
            data.put("mcode",mcode);
            data.put("password",password);
            return data;
        }
        return null;
    }

    /**
     * 添加店铺
     * @param store
     * @return
     */
    @Override
    public JSONObject addStore(JSONObject store) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("data", store);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE,ACC_MERCHANT_STORE_ADD,params,soaParam);
        System.out.println("App添加店铺返回数据"+res);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONObject) res.getData();
        }
        return null;
    }

    /**
     * 搜索店铺从soa和百度搜索
     * @param shopName 店铺名称
     * @param city 城市
     * @param pageIndex 页码
     * @param limit size
     * @param lastId
     * @return
     */
    @Override
    public JSONArray searchStores(String shopName, String city, int pageIndex, int limit, String lastId) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("shopName", shopName);
        params.put("city", city);
        params.put("lastId", lastId);
        params.put("pageIndex", pageIndex);
        params.put("limit", limit);
        ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_STORES_SEARCH_URL, params,soaParam);
        System.out.println("---searchStores:"+res.toString());
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            JSONArray stores = (JSONArray) res.getData();
            Iterator<Object> iterator = stores.iterator();
            while (iterator.hasNext()){
                JSONObject store = (JSONObject) iterator.next();
                String busiLicense = store.getString("busiLicense");
                if(StringUtils.isNotEmpty(busiLicense)){
                    store.put("busiLicense",ALIYUN_URL+busiLicense);
                }
                String busiImgs = store.getString("busiImgs");
                StringBuffer sb = new StringBuffer();
                if(!StringUtils.isEmpty(busiImgs)){
                    String[] imgs = busiImgs.split(",");
                    for(String img : imgs){
                        sb.append(ALIYUN_URL).append(img).append(",");
                    }
                    store.put("busiImgs",sb.toString());
                }
                //处理行业信息格式不统一问题
                String bizClassify = store.getString("bizClassify");
                if (!StringUtils.isEmpty(bizClassify)) {
                	//校验bizClassify为jsonArray格式还是jsonObject格式
                	char[] strChar = bizClassify.substring(0, 1).toCharArray(); 
                    char firstChar = strChar[0]; 
                    if (firstChar== '{') {
						JSONObject bizClassifyJO = JSONObject.parseObject(bizClassify);
						JSONArray bizClassifyJA = new JSONArray();
						bizClassifyJA.add(bizClassifyJO);
						System.out.println("bizClassifyJA:"+bizClassifyJA);
						store.put("bizClassify", bizClassifyJA);
					}
				}
            }
            return stores;
        }
        return null;
    }
    
    /**
     * 更新店铺信息
     * @param store
     * @param storeId
     * @return
     */
    @Override
    public JSONObject updateStore(JSONObject store, String storeId) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("data", store);
        params.put("storeId",storeId);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_MERCHANT_STORE_UPDATE, params, soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONObject) res.getData();
        }
        return null;
    }

    /**
     * 获取行业列表
     * @return
     */
    @Override
    public JSONArray getBizClassify() {
        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_BIZ_CLASSIFY, params, soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONArray) res.getData();
        }
        return null;
    }

    /**
     * 获取行业列表(新)
     */
    @Override
    public JSONArray getBizClassifyList() {
        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_BIZ_CLASSIFY_NEW, params, soaParam);
        System.out.println("-------getBizClassifyList:"+res.toString());
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONArray) res.getData();
        }
        return null;
    }
    
    /**
     * 获取门店绑定pos数量
     * @param mcode
     * @return
     */
    @Override
    public int getStoreCount(String mcode) {

        int count = 0;
        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("mcodes",mcode);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_MERCHANT_STORE_COUNT, params,soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            JSONArray data = (JSONArray) res.getData();
            count = data.getJSONObject(0).getIntValue("deviceCount");
        }
        return count;
    }

    /**
     * 获取门店绑定的设备信息
     * @param storeIds
     * @return
     */
    @Override
    public JSONArray getDevicesByStoreIds(String storeIds){
    	JSONObject devices =null;
    	JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("storeIds",storeIds);
	    ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_STORE_DEVICE, params,soaParam);
	    if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
	      	JSONArray data = (JSONArray) res.getData();
            devices = data.getJSONObject(0);
            JSONArray posList = devices.getJSONArray("posLst");
	       	return posList;
	    }
    	return null;
    }
}
